package com.ge.med.cchelper.util;


import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.console.ConsolePlugin;
import org.eclipse.ui.console.IConsole;
import org.eclipse.ui.console.IConsoleManager;
import org.eclipse.ui.console.MessageConsole;
import org.eclipse.ui.console.MessageConsoleStream;

public class LogUtil {
	
	public static final String CONSOLE_NAME = "cchelper for CT software team";
	public final static Color redColor = new Color(null, 255,0,0);
	public final static Color blueColor = new Color(null, 0,0,255);
	
	private static MessageConsole findConsole(String name) {
		ConsolePlugin plugin = ConsolePlugin.getDefault();
		if(plugin==null)return null;
		IConsoleManager conMan = plugin.getConsoleManager();
		IConsole[] existing = conMan.getConsoles();
		for (int i = 0; i < existing.length; i++)
			if (name.equals(existing[i].getName()))
				return (MessageConsole) existing[i];
		// no console found, so create a new one
		MessageConsole myConsole = new MessageConsole(name, null);
		myConsole.setWaterMarks(5000, 8000);
		conMan.addConsoles(new IConsole[] { myConsole });
		return myConsole;
	}

	public static void out(String message) {
		MessageConsole myConsole = findConsole(CONSOLE_NAME);
		if(myConsole==null){
			System.out.println(message);
			return;
		}
		MessageConsoleStream out = myConsole.newMessageStream();
		out.println(message);
	}
	
	public static void host(String message) {
		MessageConsole myConsole = findConsole(CONSOLE_NAME);
		if(myConsole==null){
			System.out.println(message);
			return;
		}
		MessageConsoleStream out = myConsole.newMessageStream();
		 Display.getDefault().asyncExec(new CCRunnabel(out,blueColor));  
		out.println(message);
	}
	
	public static void err(String message) {
		MessageConsoleStream out = LogUtil.err();
		if(out==null){
			System.err.println(message);
			return;
		}
		out.println(message);
	}
	
	public static MessageConsoleStream err() {
		MessageConsole myConsole = findConsole(CONSOLE_NAME);
		if(myConsole==null){
			//System.err.println(message);
			return null;
		}
		MessageConsoleStream errout = myConsole.newMessageStream();
		 Display.getDefault().asyncExec(new CCRunnabel(errout,redColor));  
//		errout.setColor(redColor);
		return errout;
	}
	
	public static class CCRunnabel implements Runnable {
		MessageConsoleStream messageConsole;
		Color color;

		public CCRunnabel(MessageConsoleStream messageConsole,Color color) {
			this.messageConsole = messageConsole;
			this.color = color;
		}

		
		public void run() {
			messageConsole.setColor(color);
		}

	}
}
